package threads;

import java.util.Observable;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * This is adapted from http://javabeanz.wordpress.com/2010/02/19/threadpoolexecutor-basics/ 
 * monitor thread. To monitor the status of {@link ThreadPoolExecutor}
 * and its status.
 * 
 */
public class Monitor extends Observable implements Runnable, Comparable
{
    ThreadPoolExecutor executor;

    public Monitor(ThreadPoolExecutor executor)
    {
        this.executor = executor;
    }

    @Override
    public void run()
    {
        try
        {
            do
            {
                System.out.println(
                    String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                        this.executor.getPoolSize(),
                        this.executor.getCorePoolSize(),
                        this.executor.getActiveCount(),
                        this.executor.getCompletedTaskCount(),
                        this.executor.getTaskCount(),
                        this.executor.isShutdown(),
                        this.executor.isTerminated()));
                Thread.sleep(1000);
                if(this.executor.getActiveCount() == 1)
                {
                	Thread.sleep(1000);
                	//double rest
                	if(this.executor.getActiveCount() == 1){
                		finialize();
                		break;
                	}
                }
            }
            while (true);
        }
        catch (Exception e)
        {
        	
        }
    }
    
    private void finialize(){
    	//executor.shutdown();
    	this.setChanged();
    	this.notifyObservers();
    }

	@Override
	public int compareTo(Object arg0) {
		// TODO Auto-generated method stub
		return 1;
	}
}